<?php
// +----------------------------------------------------------------------
// | 产品管理模型
// +----------------------------------------------------------------------

namespace Admins\Model;

use Common\Model\RelationModel;

class WorksModel extends  RelationModel{

    //array(验证字段,验证规则,错误提示,[验证条件,附加规则,验证时间])
    protected $_validate = array(
        array('cateid', 'require', '栏目类别错误！', 1, 'regex', 3),
        array('title', 'require', '作品名称不能为空！', 1, 'regex', 3),
        array('image', 'require', '请上传主图！', 1, 'regex', 3)
    );
    //array(填充字段,填充内容,[填充条件,附加规则])
    protected $_auto	 =	 array(
        array('userid','0',self::MODEL_INSERT,'string'),
        array('sort','0',self::MODEL_INSERT,'string'),
        array('create_time','time',self::MODEL_INSERT,'function')
    );

    //关联属性是以当前模型为主
    protected $_link = array(
        //关联操作步骤
        'works_makestep'=>array(
            'mapping_type'      => self::HAS_MANY,
            'foreign_key'       => 'workid',
            'class_name'        => 'works_makestep',
            'mapping_fields'    => array('id','scontent','simage')
            ),
        //关联材料
        'works_materials'=>array(
            'mapping_type'  => self::HAS_MANY,
            'foreign_key'   => 'workid',
            'class_name'    => 'works_materials',
            'mapping_fields'=>'id,mname,mvalue'
            )
    );

    /**
     * 添加作品信息模型
     * @param $data 页面POST的数
     * @return boolean|error
     */
    public function addModel($data) {
        if (empty($data)) {
            $this->error = '添加数据不能为空！';
            return false;
        }
        //终极栏目设置
        if(empty($data['cateid'])){
            $this->error='栏目错误,请关闭本页再试';
            return false;
        }
        if(strlen($data['title'])<5 || strlen($data['title'])>30){
            $this->error='作品名称必须大于5且小于30个字符';
            return false;
        }
        if(empty($data['image'])){
            $this->error='请上传作品主图';
            return false;
        }
        $mname=$data['mname'];
        $mvalue=$data['mvalue'];
        $simage=$data['simage'];
        $scontent=$data['scontent'];
        $result = $this->create($data, 1);
        if ($result) {
            //添加数据
            $workid = $this->add($result);
            if ($workid) {
                //更新附件状态
                if ($data['image']) {
                    //更新主图与附件关联表
                    service("Attachment")->api_update('', 'works-' . $workid, 1);
                }
                //更新材料
                if($mname){
                    $datas['workid']=$workid;
                    foreach($mname as $key=>$value){
                        //添加附件到产品附件表
                        $datas['mname']=$value;
                        $datas['mvalue']=$mvalue[$key];
                        M('works_materials')->data($datas)->add();
                    }
                }
                unset($datas);
                //更新步骤
                if($scontent){
                    $arr['workid']=$workid;
                    foreach($scontent as $key=>$value){
                        //添加附件到产品附件表
                        $arr['scontent']=$value;
                        $arr['simage']=$simage[$key];
                        M('works_makestep')->data($arr)->add();
                    }
                }
                return $workid;
            } else {
                $this->error = '产品添加失败';
                return false;
            }
        } else {
            return false;
        }
    }


    /**
     * 更新作品模型
     * @param $post
     * @return bool
     */
    public function editModel($data){
        if(empty($data['workid'])){
            $this->error='获取产品失败';
            return false;
        }

        if(empty($data['image'])){
            $this->error='请上传产品主图';
            return false;
        }
        //yf start
        foreach($data['mname'] as $k => $v)
        {
        	if(empty($v) && empty($data['mvalue'][$k]))
        	{
        		unset($data['mname'][$k]);
        		unset($data['mvalue'][$k]);
        	}
        	elseif(empty($v) || empty($data['mvalue'][$k]))
        	{
        		$this->error='请补全作品用料名称或者是用量';
        		return false;
        	}
        }
        //yf end
        //yf start
        foreach($data['simage'] as $kk => $vv)
        {
        	if(empty($vv) && empty($data['scontent'][$kk]))
        	{
        		unset($data['simage'][$kk]);
        		unset($data['scontent'][$kk]);
        	}
        	elseif(empty($vv) || empty($data['scontent'][$kk]))
        	{
        		$this->error='请补全步骤图或者是步骤描述';
        		return false;
        	}
        }
        unset($data['files']);
        $workid=$data['workid'];
        $mname=$data['mname'];
        $mvalue=$data['mvalue'];
        $mtid=$data['materials_id'];
        $simage=$data['simage'];
        $scontent=$data['scontent'];
        $stepid=$data['stepid'];
        $today=date('Y年m月d日',time());
        //获取商品原来状态及会员ID
        $item=M('Works')->field('userid,status,type,ifindex,iftj,title,modify_time')->where(array('workid'=>$workid))->find();
        if($item['type']==1){
            $upoint=10;
        }else{
            $upoint=10;
        }

        $result = $this->create($data, 2);
        if ($result) {
            //修改数据
            $where['workid']=$workid;
            $status=$this->data($result)->where($where)->save();
            //更新记录,记得如果是TRUE就为===,如果为FLASH则为!==,并不是!=
            if(false!==$status){
                //增加会员积分与商量数
                if($data['status']==true && $item['status']!=true){
                	if(empty($item['modify_time']))
                	{
                   		$savearr['worksnum'] = array('exp','worksnum+1');
                    	$savearr['upoint'] = array('exp','upoint+'.$upoint.'');
             //       service('Passport')->userDynamic($item['userid'],10,$item['title'].'通过审核获得10个积分',1,'workspass');
                    insertSysmsg($item['userid'],'恭喜作品通过审核','恭喜您的作品《'.$data['title'].'》于'.$today.'通过审核，继续努力哦！详情猛戳 <a href="http://www.hongbeiq.com">www.hongbeiq.com</a>');

                    	service('Passport')->userDynamic($item['userid'],10, '做过'.$item['title'],1,'workadd',$workid);
                	}

                }elseif($data['status']!=true && $item['status']==true){
                    $savearr['worksnum'] = array('exp','worksnum-1');
                    $savearr['upoint'] = array('exp','upoint-'.$upoint.'');
               //     service('Passport')->userDynamic($item['userid'],10,$item['title'].'不通过审核扣除10个积分',2,'workspass');
                }
                M('User')->where(array('userid'=>$item['userid']))->save($savearr);

                //获取头条推荐
                if($data['iftj']==true && $item['iftj']==false){
                    $savetj['upoint'] = array('exp','upoint+20');
                    service('Passport')->userDynamic($item['userid'],20,$item['title'].'推荐到首页获得30个积分',1,'worksindex');
                    insertSysmsg($item['userid'],'恭喜作品获得头条推荐','恭喜您的作品《'.$item['title'].'》于'.$today.'被推荐到烘焙圈头条，继续努力哦！详情猛戳 <a href="http://www.hongbeiq.com">www.hongbeiq.com</a>');
                    M('User')->where(array('userid'=>$item['userid']))->save($savetj);
                }

                //获取首页推荐
                if($data['ifindex']==true && $item['ifindex']==false){
                    $saveinfo['upoint'] = array('exp','upoint+30');
                    service('Passport')->userDynamic($item['userid'],30,$item['title'].'推荐到首页获得30个积分',1,'worksindex');
                    insertSysmsg($item['userid'],'恭喜作品获得首页推荐','恭喜您的作品《'.$item['title'].'》于'.$today.'被推荐到烘焙圈首页，继续努力哦！详情猛戳 <a href="http://www.hongbeiq.com">www.hongbeiq.com</a>');
                    M('User')->where(array('userid'=>$item['userid']))->save($saveinfo);
                }


                //更新附件状态
                if ($data['image'] || $data['simage']) {
                    //更新主图与附件关联表
                    service("Attachment")->api_update('', 'works-' . $workid, 1);
                }
                //更新材料
                if($mname){
                    $datas['workid']=$workid;
                    foreach($mname as $key=>$value){
                        $datas['mname']=$value;
                        $datas['mvalue']=$mvalue[$key];
                        $datas['id']=$mtid[$key];
                        if(!empty($datas['id'])){
                            M('works_materials')->data($datas)->save();
                        }else{
                            M('works_materials')->data($datas)->add();
                        }
                    }
                }
                unset($datas);
                //更新步骤
                if($scontent){
                    $arr['workid']=$workid;
                    foreach($scontent as $k=>$v){
                        $arr['scontent']=$v;
                        $arr['simage']=$simage[$k];
                        $arr['id']=$stepid[$k];
                        if(!empty($arr['id'])){
                            M('works_makestep')->data($arr)->save();
                        }else{
                            M('works_makestep')->data($arr)->add();
                        }
                    }
                }
                return true;
            } else {
                $this->error = '产品更新失败';
                return false;
            }
        } else {
            return false;
        }

    }

    /**
     * 删除产品
     * @param $data
     * @return bool
     */
    public function deleteModel($data){
        if(empty($data)){
            $this->error='作品删除失败';
            return false;
        }
        $today=date('Y年m月d日',time());
        $where['workid']=$data;
        $item=$this->field('userid,status,type,title')->where($where)->find();
        if($item['type']==1){
            $upoint=10;
        }else{
            $upoint=10;
        }
        if($item['status']==true){
            $savearr['worksnum'] = array('exp','worksnum-1');
            $savearr['upoint'] = array('exp','upoint-'.$upoint.'');
      //      service('Passport')->userDynamic($item['userid'],20,'发布违规作品扣除20个积分',2,'worksdel');
            insertSysmsg($item['userid'],'您的作品被删除','很遗憾您的作品《'.$item['title'].'》于'.$today.'日因违反烘焙圈相关规则被删除！详情请查阅烘焙圈相关协议。');

        }
        $status=$this->relation(true)->where($where)->delete();
        if($status!==false){
            //减去数量与积分操作
            M('User')->where(array('userid'=>$item['userid']))->save($savearr);
            //删除产品主图
            service("Attachment")->api_delete('works-' . $data);
            return true;
        }else{
            return false;
        }
    }

    /**
     * 删除操作步骤
     * @param $id
     * @return bool
     */
    public function deleteMakeStepModel($id){
        if(empty($id)){
            $this->error='信息删除请求失败';
            return false;
        }
        $where['id']=$id;
        $status=M('WorksMakestep')->where($where)->delete();
        if($status!==false){
            return true;
        }else{
            return false;
        }
    }


}
